<template>
  <div class="Box">
    <!-- 顶部搜索/添加 -->
    <div class="SearchBox flex-LAR" v-show="tableData.length > 0">
      <el-input v-model="SearchKeyWord.searchValue" placeholder="请输入搜索内容" class="input-with-select"
        @keyup.enter="SearchEventList">
        <template #prepend>
          <el-select v-model="SearchKeyWord.selectKey" style="width: 6.25rem">
            <el-option v-for="(item, index) in SearcSelect" :key="index" :label="item.label" :value="item.prop" />
          </el-select>
        </template>
        <template #append>
          <el-button class="searchBtn" :icon="Search" @click="SearchEventList" />
        </template>
      </el-input>
      <el-button class="addBtn" type="primary" :icon="Plus" @click="handleAdd" />
    </div>
    <!-- 分页 -->
    <div class="PageBox">
      <el-pagination :hide-on-single-page="true" v-model:current-page="page.currentPage" v-model:page="page.pageNum"
        v-model:limit="page.pageSize" v-model:total="page.total" :page-count="Math.ceil(page.total / page.pageSize)" />
    </div>
    <!-- 表格 -->
    <div class="TableBox">
      <cy-table class="Table" row-key="event_id" :data="tableData" :columns="ruleTable.columns" :loading="loading"
        @selection-change="handleSelectionChange" />
    </div>
    <!-- 修改抽屉 -->
    <el-drawer v-model="editdrawer" title="edit" :with-header="false">
      <cy-form class="EditForm" label-width="auto" style="max-width: 31.25rem">
        <cy-form-item v-for="(item, index) in editFormColumns" :key="index" :label="item.label">
          <!-- 时间选择器 -->
          <template v-if="['PublishTime', 'ReceiveTime', 'CompleteTime'].includes(item.prop)">
            <el-date-picker style="width: 50rem;" v-model="editform[item.prop]" type="date" />
          </template>
          <!-- 输入框 -->
          <template v-else>
            <el-input v-model="editform[item.prop]" :readonly="item.isReadonly ? item.isReadonly : false" />
          </template>

        </cy-form-item>
        <cy-form-item>
          <!-- 操作按钮 -->
          <el-button type="primary" @click="EditSubmit">确认</el-button>
          <el-button @click="editdrawer = false">取消</el-button>
        </cy-form-item>
      </cy-form>
    </el-drawer>
    <!-- 添加抽屉 -->
    <el-drawer v-model="adddrawer" title="edit" :with-header="false">
      <cy-form class="EditForm" label-width="auto" style="max-width: 31.25rem">
        <cy-form-item v-for="(item, index) in addFormColumns" :key="index" :label="item.label">
          <!-- 时间选择器 -->
          <template v-if="['PublishTime', 'ReceiveTime', 'CompleteTime'].includes(item.prop)">
            <el-date-picker style="width: 50rem;" v-model="addform[item.prop]" type="date" />
          </template>
          <!-- 输入框 -->
          <template v-else>
            <el-input v-model="addform[item.prop]" :readonly="item.isReadonly ? item.isReadonly : false" />
          </template>
        </cy-form-item>
        <cy-form-item>
          <el-button type="primary" @click="AddSubmit">确认</el-button>
          <el-button @click="adddrawer = false">取消</el-button>
        </cy-form-item>
      </cy-form>
    </el-drawer>
  </div>
</template>

<script lang="tsx" setup>
import { ref, reactive, watch, onMounted } from "vue";
import type { TableInstance } from "element-plus";

import CyTable from "@/components/table";
import CyForm from "@/components/form";
import CyFormItem from "@/components/form-item";

import { ElMessage, ElMessageBox, VLoad } from "element-plus";
import { Search, Plus } from "@element-plus/icons-vue";
import {
  getEventAllAPI,
  getEventPageAPI,
  getEventKeyPageAPI,
  UpdateEventByIdAPI,
  DeleteEventByIdAPI,
  DeleteEventMoreByIdAPI,
  AddEventAPI,
  getEventTypeAPI,
} from "@/api/quickevent";
import { assignObject } from "@/utils/object";


const tableData = ref([]);
const tableRef = ref<TableInstance>();
const loading = ref(true);
const multipleSelection = ref([]);
const editdrawer = ref(false);
const adddrawer = ref(false);
const TypeList = ref()
const page = reactive({
  currentPage: 1,
  pageNum: 1,
  pageSize: 10,
  total: 0,
});
// 筛选
const SearchKeyWord = reactive({
  selectKey: "event_id",
  searchValue: "",
});
// 表格配置
const ruleTable = reactive({
  columns: [
    // 全选框列
    {
      type: "selection",
      width: 55,
    },
    // 数据列
    // { prop: "event_id", label: "事件ID" },
    // { prop: "event_type_id", label: "事件类型ID" },
    { prop: "event_type_name", label: "事件名" },
    { prop: "description", label: "描述", width: 800 },
    { prop: "type_level", label: "官方分级" },
    { prop: "risk_level", label: "危害等级" },
    { prop: "group_type", label: "灾害类型" },
    // 状态列
    {
      prop: "risk_level",
      label: "危害等级",
      render: ({ row }) => (
        <span class={ClassRisk(row.risk_level)}>
          {row.risk_level === "5" ? "极大" :row.risk_level === "4" ?"高":row.risk_level === "3"?'中':row.risk_level === "2"?'低':'极小'}
        </span>
      ),
    },
    // 操作列
    // {
    //   label: "操作",
    //   align: "center",
    //   headerRender: () => (
    //     <div style="text-align: center;">
    //       <div class="OptionsBtn" onClick={MoreDelete} style="display: inline-block;">
    //         批量删除
    //       </div>
    //     </div>
    //   ),
    //   render: ({ row, index }) => (
    //     <div>
    //       <el-button onClick={() => handleEdit(index, row)}>修改</el-button>
    //       <el-button type="danger" onClick={() => handleDelete(index, row)}>
    //         删除
    //       </el-button>
    //     </div>
    //   ),
    // },
  ],
});
const getTipList = () => {
  getEventTypeAPI().then((res) => {
    TypeList.value = res.data.data
  })
}
// 分页查询
const getEventPage = () => {
  loading.value = true;
  getEventPageAPI({
    page: page.currentPage,
    pageSize: page.pageSize,
    orderBy: "event_id ASC",
  })
    .then((res) => {
      const { row, total } = res.data;
      row.forEach(item => {
        const eventType = TypeList.value?.find(eventType => eventType.event_type_id === item.event_type_id);
        if (eventType) {
          item.event_type_name = eventType.event_type_name;
          item.group_type = eventType.group_type;
        }
      });
      tableData.value = row;
      page.total = total;
    })
    .finally(() => (loading.value = false));
};
// 选择框选中
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
};

/* 修改 */
const editform = reactive({
  event_id: '',
  event_type_id: '',
  description: '',
  type_level: '',
  risk_level: '',
});
const editFormColumns = [
  { prop: "event_id", label: "事件ID" },
  { prop: "event_type_id", label: "事件类型ID" },
  { prop: "description", label: "描述" },
  { prop: "type_level", label: "官方分级" },
  { prop: "risk_level", label: "危害等级" },
];
const handleEdit = (index: number, row: any) => {
  assignObject(editform, row);
  editdrawer.value = true;
};
// 确认修改提交
const EditSubmit = () => {
  // 提交后台
  UpdateEventByIdAPI(editform).then((res) => {
    const { code, message } = res.data;
    getEventPage();
    ElMessage.success(message);
    editdrawer.value = false;
  });
};
/* 添加 */
const addform = reactive({
  event_id: '',
  event_type_id: '',
  description: '',
  type_level: '',
  risk_level: '',
});
const addFormColumns = [
  { prop: "event_id", label: "事件ID" },
  { prop: "event_type_id", label: "事件类型ID" },
  { prop: "description", label: "描述" },
  { prop: "type_level", label: "官方分级" },
  { prop: "risk_level", label: "危害等级" },
];
// 添加任务
const handleAdd = () => {
  adddrawer.value = true;
};
// 确认添加提交
const AddSubmit = () => {
  AddEventAPI(addform).then((res) => {
    const { code, message } = res.data;
    ElMessage.success(message);
    getEventPage();
    adddrawer.value = false;
  });
};
/* 删除 */
const handleDelete = (index: number, row: any) => {
  // 警告提示
  ElMessageBox.confirm("删除操作无法撤回，是否继续?", "Warning", {
    confirmButtonText: "OK",
    cancelButtonText: "Cancel",
    type: "warning",
  })
    .then(() => {
      // 执行删除
      DeleteEventByIdAPI(row.event_id).then((res) => {
        const { code, message } = res.data;
        getEventPage();
        ElMessage.success(message);
      });
    })
    .catch(() => {
      // 取消
      ElMessage({
        type: "info",
        message: "取消删除操作",
      });
    });
};
const MoreDelete = () => {
  if (!multipleSelection.value || multipleSelection.value.length === 0) {
    ElMessage.warning("未选择目标");
    return;
  }
  const ids = multipleSelection.value.reduce(
    (acc, item) => [...acc, item.event_id],
    []
  );
  // 警告提示
  ElMessageBox.confirm("删除操作无法撤回，是否继续?", "Warning", {
    confirmButtonText: "OK",
    cancelButtonText: "Cancel",
    type: "warning",
  })
    .then(() => {
      // 执行删除
      DeleteEventMoreByIdAPI(ids).then((res) => {
        const { code, message } = res.data;
        getEventPage();
        ElMessage.success(message);
      });
    })
    .catch(() => {
      // 取消
      ElMessage({
        type: "info",
        message: "取消删除操作",
      });
    });
};

/* 查询 */
const SearcSelect = [
  { prop: "event_id", label: "事件ID" },
  { prop: "event_type_id", label: "事件类型ID" },
  { prop: "description", label: "描述" },
  { prop: "type_level", label: "官方分级" },
  { prop: "risk_level", label: "危害等级" },
];
const SearchEventList = () => {
  if (!SearchKeyWord.searchValue) {
    getEventPage();
    return;
  }
  loading.value = true;
  getEventKeyPageAPI({
    SearchKey: SearchKeyWord.selectKey,
    SearchValue: SearchKeyWord.searchValue,
    page: page.currentPage,
    pageSize: page.pageSize,
    orderBy: "event_id ASC",
  })
    .then((res) => {
      const { row, total } = res.data;
      row.forEach(item => {
        const eventType = TypeList.value?.find(eventType => eventType.event_type_id === item.event_type_id);
        if (eventType) {
          item.event_type_name = eventType.event_type_name;
          item.group_type = eventType.group_type;
        }
      });
      tableData.value = row;
      page.total = total;
    })
    .finally(() => (loading.value = false));
};
// 用户状态动态类名
const ClassRisk = (level: string) => {
  switch (level) {
    case "1":
    case "2":
    case "3":
      return "status-active";
    default:
      return "status-unactive";
  }
};
// 监听分页
watch(
  () => page.currentPage,
  () => {
    if (!SearchKeyWord.searchValue) {
      getEventPage();
    } else {
      SearchEventList()
    }
  }
);
onMounted(() => {
  getTipList()
  setTimeout(() => {
    getEventPage();
  }, 1000);
});
</script>
<style scoped lang="scss">
.Box {
  position: relative;

  .SearchBox {
    width: 100%;
    height: 60px;
    background-color: #fff;
    border-bottom: 1px solid #eee;

    .el-input {
      width: 350px;
      margin-left: 0.5rem;
    }

    .searchBtn {
      color: rgb(15, 153, 245);
    }

    .addBtn {
      margin-right: 1rem;
    }
  }

  .PageBox {
    background-color: #fff;
    padding-left: 30%;
    margin: 1rem;
  }

  .TableBox {
    .Table {
      width: 100%;
      min-height: 25rem;
      border-top: 1px solid #eee;
    }

    :deep(.status-active) {
      color: green;
    }

    :deep(.status-unactive) {
      color: #f56c6c;
    }

    :deep(.OptionsBtn) {
      height: 30px;
      line-height: 30px;
      width: 8.125rem;
      border: 1px solid #f56c6c;
      border-radius: 0.3rem;
      text-align: center;
      background-color: #f56c6c;
      color: #fff;
      cursor: pointer;

      &:hover {
        background-color: #e78d8d;
        border: 1px solid #e78d8d;
      }
    }
  }

  .EditForm {
    :deep(.el-form-item__content) {
      display: flex;
      justify-content: center;
      align-content: center;
    }
  }
}
</style>
